package org.abettor.pushbox.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Random;

import org.abettor.android.ads.YoumiManager;
import org.abettor.pushbox.map.Boxmap;
import org.abettor.pushbox.map.Step;
import org.abettor.pushbox.view.ShowResultView;
import org.abettor.pushbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

public abstract class AbstractShowResultActivity extends Activity {
	protected ShowResultView m_boxView;// 用来显示boxview
	protected Boxmap m_map, origenMap;// 推箱子的地图
	// protected PushBoxMapBeanManage manage;
	protected ImageButton mPlayButton, mNxtButton, mPreButton, mStopButton;
	protected List<Step> stepList = null;
	protected int stepIndex = -1;// 步骤列表
	protected Handler mHandler = new Handler();
	protected int status = STATUS_STOP;// 状态
	private final long DELAY_TIME = 700;
	private final static int STATUS_STOP = 0, STATUS_RUN = 1;
	private ProgressDialog progress;// 进度条对话框
	private final int SHOW_AD = 13579;
	private YoumiManager youmi = new YoumiManager(this);
	private Handler youmiHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == SHOW_AD) {
				// 按照一定的概率显示广告
				Random rand = new Random(System.currentTimeMillis());
				int val = rand.nextInt(99);
				if (val < 70) {
					youmi.showYoumi(YoumiManager.Position.middle, Color.WHITE,
							Color.BLACK, 0xAA);
				}
			}

			super.handleMessage(msg);
		}
	};
	private Thread youmiDelayThread = new Thread() {
		@Override
		public void run() {
			try {
				Thread.sleep(200);
				Message msg = new Message();
				msg.what = SHOW_AD;
				youmiHandle.sendMessage(msg);
			} catch (InterruptedException e) {
				Log.d(this.getClass().getName(), "", e);
			}
		}
	};

	// 点击按钮的操作
	private class ButtonOnTouchListener implements OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (v == mPlayButton) {
					if (status == STATUS_STOP) {
						play();
					} else {
						pause();
					}
				} else if (v == mNxtButton) {
					nxt();
				} else if (v == mPreButton) {
					pre();
				} else if (v == mStopButton) {
					stop();
				}
			}
			return true;
		}
	}

	// 设置显示的状态
	private void setPlayButtonBack() {
		if (status == STATUS_RUN) {
			mPlayButton.setImageResource(android.R.drawable.ic_media_pause);
		} else {
			mPlayButton.setImageResource(android.R.drawable.ic_media_play);
		}
	}

	// 进行运行的操作
	private void play() {
		if (status == STATUS_RUN) {
			return;
		}
		status = STATUS_RUN;
		setPlayButtonBack();
		if (stepIndex == stepList.size() - 1) {
			reDrawMap();
			stepIndex = -1;
		}
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (status == STATUS_STOP) {// 已经停止了的状态直接返回
					return;
				}
				stepIndex = stepIndex + 1;
				Step step = stepList.get(stepIndex);
				m_boxView.forwardStep(step);// 向下一步的操作
				if (stepIndex == stepList.size() - 1) {
					status = STATUS_STOP;
					setPlayButtonBack();
					return;
				}
				mHandler.postDelayed(this, DELAY_TIME);
			}
		});
	}

	// 进行停止的操作
	private void stop() {
		status = STATUS_STOP;
		stepIndex = -1;
		reDrawMap();
		setPlayButtonBack();
	}

	// 重新绘制地图
	private void reDrawMap() {
		m_map = Boxmap.copy(origenMap);
		m_boxView.setMap(m_map);
		m_boxView.generateBitmap();
	}

	// 进行暂停的操作
	private void pause() {
		status = STATUS_STOP;
		setPlayButtonBack();
	}

	// 上一步的操作
	private void pre() {
		status = STATUS_STOP;
		setPlayButtonBack();
		if (stepIndex == -1) {
			Toast.makeText(this, R.string.show_result_firststep,
					Toast.LENGTH_SHORT).show();
			return;
		}
		Step step = stepList.get(stepIndex);
		Step step1 = null;
		if (stepIndex - 1 >= 0) {
			step1 = stepList.get(stepIndex - 1);
		}
		m_boxView.backStep(step, step1);// 向下一步的操作
		stepIndex = stepIndex - 1;
	}

	// 下一步的操作
	private void nxt() {
		status = STATUS_STOP;
		setPlayButtonBack();
		if (stepIndex == stepList.size() - 1) {
			Toast.makeText(this, R.string.show_result_laststep,
					Toast.LENGTH_SHORT).show();
			return;
		}
		stepIndex = stepIndex + 1;
		Step step = stepList.get(stepIndex);
		m_boxView.forwardStep(step);// 向下一步的操作
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_result_activity);
		m_boxView = (ShowResultView) findViewById(R.id.boxview);
		init();
	}

	// 进行初始化操作
	private void init() {
		m_map = initMap();
		origenMap = Boxmap.copy(m_map);// 保存一个原始的地图
		m_boxView.setMap(m_map);
		// 读取step列表
		// stepList = initStep();
		readStepList();
		mPlayButton = (ImageButton) findViewById(R.id.play_button);
		mPlayButton.setOnTouchListener(new ButtonOnTouchListener());
		mNxtButton = (ImageButton) findViewById(R.id.nxt_button);
		mNxtButton.setOnTouchListener(new ButtonOnTouchListener());
		mPreButton = (ImageButton) findViewById(R.id.pre_button);
		mPreButton.setOnTouchListener(new ButtonOnTouchListener());
		mStopButton = (ImageButton) findViewById(R.id.stop_button);
		mStopButton.setOnTouchListener(new ButtonOnTouchListener());
		youmiDelayThread.start();
	}

	// 读取步骤列表的操作
	private void readStepList() {
		progress = new ProgressDialog(this);
		progress.setTitle(R.string.answer_load);
		progress.setMessage(this.getText(R.string.answer_loading));
		progress.show();
		Thread thread = new Thread() {
			@Override
			public void run() {
				stepList = initStep();
				progress.dismiss();
				if (stepList == null) {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							showReadStepErrorDialog();
						}
					});
				} else {
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							reDrawMap();
						}
					});
				}
			}
		};
		thread.start();
	}

	// 显示读取列表错误的操作
	private void showReadStepErrorDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog alert = builder.create();
		alert.setTitle(R.string.add_nick);
		alert.setMessage(AbstractShowResultActivity.this
				.getText(R.string.add_nick_fail));
		alert.setButton(DialogInterface.BUTTON_POSITIVE,
				AbstractShowResultActivity.this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AbstractShowResultActivity.this.finish();
					}
				});
		alert.show();
	}

	/**
	 * 初始化地图的操作
	 * 
	 * @return
	 */
	protected abstract Boxmap initMap();

	/**
	 * 初始化步骤的操作
	 * 
	 * @return
	 */
	protected abstract List<Step> initStep();

	// 读取地图文件
	protected byte[] readFileByPath(String filename) throws IOException {
		File file = new File(filename);
		if (!file.exists()) {
			return null;
		}
		InputStream in = new FileInputStream(file);
		ByteArrayOutputStream byteout = new ByteArrayOutputStream();
		int value = 0;
		while ((value = in.read()) != -1) {
			byteout.write(value);
		}
		return byteout.toByteArray();
	}
}
